package com.xcl.controller;

import com.xcl.pojo.Result;
import com.xcl.pojo.User;
import com.xcl.service.UserService;
import com.xcl.service.impl.UserServiceImpl;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Pattern;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@Validated
@CrossOrigin
public class UserController {


    @Autowired
    UserService userService;

    //处理注册请求的方法
    @RequestMapping("/register")
    public Result register(@Valid @RequestBody User user){  //请求参数的校验  账号和密码长度 4-16位
        //检查账号是否重复
        User u = userService.findUserByName(user.getUserName());
        if(u == null){  //没查到，账号可以用
            Integer r = userService.register(user.getUserName(),user.getPassword());
            if(r > 0){  //注册成功
                return Result.success();
            }else{  //注册失败
                return Result.error("注册失败!");
            }
        }else{ //账号已经被占用
            return Result.error("账号已经被占用!");
        }
    }


    //登录
    @RequestMapping("/login")
    public Result login(@Valid @RequestBody User user){
        //查询有没有输入的账号
        User u = userService.findUserByName(user.getUserName());
        //没查到，表示账号不对
        if(u == null){
            return Result.error("账号不存在");
        }else{  //能查到，表示有这个账号
            //检查密码是否正确
            boolean b = userService.checkPassword(user.getPassword(),u.getPassword());
            if(b){
                return Result.success(u);
            }else{
                return Result.error("密码不正确");
            }
        }
    }



}
